package com.flyco.modules.task.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.modules.oms.entity.OmsOrder;
import com.flyco.modules.oms.entity.OmsOrderItem;
import com.flyco.modules.oms.entity.OmsOrderSetting;
import com.flyco.modules.oms.entity.OmsOrderTrace;
import com.flyco.modules.oms.mapper.OmsOrderMapper;
import com.flyco.modules.oms.mapper.OmsOrderSettingMapper;
import com.flyco.modules.oms.mapper.OmsOrderTraceMapper;
import com.flyco.modules.oms.service.IOmsOrderItemService;
import com.flyco.modules.oms.service.IOmsOrderService;
import com.flyco.modules.oms.service.IOmsOrderTraceService;
import com.flyco.modules.pms.entity.PmsProduct;
import com.flyco.modules.pms.entity.StmJdWmsStock;
import com.flyco.modules.pms.service.IPmsProductService;
import com.flyco.modules.pms.service.IStmJdWmsStockService;
import com.flyco.modules.stm.entity.StmChannelPrice;
import com.flyco.modules.stm.entity.StmDealerDiscount;
import com.flyco.modules.stm.entity.StmDealerStatement;
import com.flyco.modules.stm.entity.StmStoreInfo;
import com.flyco.modules.stm.mapper.StmDealerDiscountMapper;
import com.flyco.modules.stm.mapper.StmDealerStatementMapper;
import com.flyco.modules.stm.service.IStmChannelPriceService;
import com.flyco.modules.stm.service.IStmStoreInfoService;
import com.flyco.modules.system.entity.SysLog;
import com.flyco.modules.system.mapper.SysLogMapper;
import com.flyco.modules.task.entity.ToSapConfig;
import com.flyco.modules.task.mapper.ToSapConfigMapper;
import com.flyco.modules.task.service.SapTaskService;
import com.flyco.modules.task.util.SapConvert;
import com.flyco.modules.task.util.SapWebServiceRequestUtil;
import com.flyco.modules.task.util.XStreamXmlBeanUtil;
import com.flyco.modules.task.xml.*;
import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author hui_li
 * @Date 2024/1/25 17:07
 * @Version 1.0
 */
@Slf4j
@Service
public class SapTaskServiceImpl implements SapTaskService {
    @Resource
    private ToSapConfigMapper toSapConfigMapper;
    @Autowired
    private IPmsProductService pmsProductService;
    @Resource
    private SysLogMapper sysLogMapper;
    @Autowired
    private IOmsOrderItemService omsOrderItemService;
    @Autowired
    private IStmStoreInfoService stmStoreInfoService;
    @Autowired
    private IStmJdWmsStockService wmsStockService;
    @Autowired
    private IOmsOrderService omsOrderService;
    @Autowired
    private IStmChannelPriceService stmChannelPriceService;
    @Resource
    private OmsOrderMapper omsOrderMapper;
    @Resource
    private StmDealerDiscountMapper dealerDiscountMapper;
    @Autowired
    private IOmsOrderTraceService orderTraceService;
    @Resource
    private StmDealerStatementMapper dealerStatementMapper;
    @Resource
    private OmsOrderSettingMapper omsOrderSettingMapper;
    @Resource
    private OmsOrderTraceMapper omsOrderTraceMapper;

    @Override
    public void toSapStock(Long partnerId) {
        List<String> skuCodeList = stmChannelPriceService.getSkuCodeListByPartnerId(partnerId);
        if (skuCodeList.isEmpty()) {
            return;
        }
        ToSapConfig toSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "productStock_prd"));
        getSapStockBatch(skuCodeList.stream().distinct().collect(Collectors.toList()), toSapConfig, partnerId);
    }

    @Override
    public void toSapStock(String orderId, Long partnerId) {
        List<String> skuCodeList = omsOrderItemService.selectByMainId(orderId).stream().map(OmsOrderItem::getProductSkuCode).collect(Collectors.toList());
        ToSapConfig toSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "productStock_prd"));
        getSapStockBatch(skuCodeList, toSapConfig, partnerId);
    }

    //批量查询更新商品库存
    private void getSapStockBatch(List<String> skuCodeList, ToSapConfig toSapConfig, Long partnerId) {
        if (skuCodeList.isEmpty()) {
            return;
        }
        List<OmsOrderItem> orderItems = new ArrayList<>();
        //omsOrderItemService.getProductOccupation();//获取当前订单已经占用的库存
        SapProductStockQueryXML stockQueryXML = new SapProductStockQueryXML();
        stockQueryXML.setWerks(partnerId.toString());
        SapMatnrListXML matnrListXML = new SapMatnrListXML();
        List<SapMatnrXML> codeList = new ArrayList<>();
        skuCodeList.forEach(x -> {
            SapMatnrXML matnr = new SapMatnrXML();
            matnr.setMatnr(x);
            codeList.add(matnr);
        });
        matnrListXML.setSkuCodeList(codeList);
        stockQueryXML.setMatnrList(matnrListXML);
        Map<String, String> map = sendToSap(toSapConfig, stockQueryXML);
        String message = map.get("originalResult");
        int beginIndex = message.indexOf("<OutputStock>");
        if (beginIndex > 0) {
            int endIndex = message.indexOf("</OutputStock>");
            String stockContent = message.substring(beginIndex, endIndex + 14);
            SapProductStockRespXML response = XStreamXmlBeanUtil.fromXml(stockContent, SapProductStockRespXML.class);
            if (response != null) {
                List<SapProductStockRespXML.ProductStockItem> stockItems = response.getItemList();
                List<StmJdWmsStock> skuStockList = wmsStockService.getBySkuCodeList(skuCodeList, partnerId);
                if (stockItems != null && !stockItems.isEmpty()) {
                    stockItems.forEach(stock -> {
                        //计算可用库存=sap库存-已复审订单占用
                        Integer sapStock = Double.valueOf(stock.getAtpStock()).intValue();
                        Optional<OmsOrderItem> orderItem = orderItems.stream().filter(x -> x.getProductSkuCode().equals(stock.getAtpStock())).findFirst();
                        if (orderItem.isPresent() && orderItem.get() != null) {
                            sapStock = sapStock - orderItem.get().getSendProQty();//如果当前订单有占用库存需要减掉 by martin 2024-04-08
                        }
                        List<StmJdWmsStock> tempSkuStockList = skuStockList.stream().filter(x -> x.getSkuCode().equals(stock.getMatnr()) && x.getPartnerId().equals(partnerId)).collect(Collectors.toList());
                        if (!tempSkuStockList.isEmpty()) {
                            StmJdWmsStock skuStock = tempSkuStockList.get(0);
                            if (skuStock != null) {
                                if (!skuStock.getStock().equals(sapStock) || (skuStock.getSpecNo() != null && !skuStock.getSpecNo().equals(stock.getZSlck()))) {  //如果库存有差异在更新,否则不更新
                                    skuStock.setPartnerId(partnerId);
                                    skuStock.setStock(sapStock);
                                    skuStock.setSpecNo(stock.getZSlck());
                                    skuStock.setUpdateTime(DateTime.now());
                                    wmsStockService.updateById(skuStock);
                                }
                            }
                        } else {
                            StmJdWmsStock skuStock = new StmJdWmsStock();
                            skuStock.setPartnerId(partnerId);
                            skuStock.setSkuCode(stock.getMatnr());
                            skuStock.setStatus(0);
                            skuStock.setSpecCode(stock.getMatnr());
                            skuStock.setStock(sapStock);
                            skuStock.setSpecNo(stock.getZSlck());
                            skuStock.setCreateTime(DateTime.now());
                            wmsStockService.save(skuStock);
                        }
                    });
                    skuStockList.forEach(item -> {//在返回结果中未找到数据,直接更新库存为0
                        List<SapProductStockRespXML.ProductStockItem> stockItemList = stockItems.stream().filter(x -> x.getMatnr().equals(item.getSkuCode())).collect(Collectors.toList());
                        if (stockItemList == null || stockItemList.isEmpty()) {
                            if (!item.getStock().equals(0)) {
                                item.setPartnerId(partnerId);
                                item.setStock(0);
                                item.setSpecNo("0");
                                item.setUpdateTime(DateTime.now());
                                wmsStockService.updateById(item);
                            }
                        }
                    });
                } else {//未获取到库存
                    skuCodeList.forEach(stock -> {
                        List<StmJdWmsStock> tempSkuStockList = skuStockList.stream().filter(x -> x.getSkuCode().equals(stock)).collect(Collectors.toList());
                        if (tempSkuStockList != null && !tempSkuStockList.isEmpty()) {
                            StmJdWmsStock skuStock = tempSkuStockList.get(0);
                            skuStock.setPartnerId(partnerId);
                            skuStock.setStock(0);
                            skuStock.setSpecNo("0");
                            skuStock.setUpdateTime(DateTime.now());
                            wmsStockService.updateById(skuStock);
                        }
                    });
                }
            }
        } else {
            List<StmJdWmsStock> skuStockList = wmsStockService.getBySkuCodeList(skuCodeList, partnerId);
            skuCodeList.forEach(stock -> {
                List<StmJdWmsStock> tempSkuStockList = skuStockList.stream().filter(x -> x.getSkuCode().equals(stock)).collect(Collectors.toList());
                if (tempSkuStockList != null && !tempSkuStockList.isEmpty()) {
                    StmJdWmsStock skuStock = tempSkuStockList.get(0);
                    skuStock.setPartnerId(partnerId);
                    skuStock.setStock(0);
                    skuStock.setSpecNo("0");
                    skuStock.setUpdateTime(DateTime.now());
                    wmsStockService.updateById(skuStock);
                }
            });
        }
    }

    @Override
    public Map<String, String> toSapOrder(OmsOrder order, String orderId, String userName) {
        if (order == null) {
            order = omsOrderService.getById(orderId);
        }
        List<OmsOrderItem> orderItems = omsOrderItemService.selectByMainId(order.getId());
        if (orderItems.isEmpty()) {
            return null;
        }
        List<SapOrderCreateXML> sapOrderCreateXMLs = new ArrayList<>();
        ToSapConfig toSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "sapOrderCreate_prd"));//正式环境:sapOrderCreate_prd
        StmStoreInfo storeInfo = stmStoreInfoService.getByStoreId(order.getStoreId());
        for (int i = 0; i < orderItems.size(); i++) {
            OmsOrderItem a = orderItems.get(i);
            //明细数量为0的话不传sap
            if (a.getSendProQty() == null || a.getSendProQty().equals(0)) {
                continue;
            }
            String stockCode = StringUtils.isEmpty(order.getStockCode()) ? order.getCompanyCode() : order.getStockCode();
            order.setSHIPTO(stockCode);
            order.setProductSkuCode(a.getProductSkuCode());
            order.setPOSEX(i + 1);
            //取值逻辑调整，审核的时候增加字段，分配数量
            order.setProductSkuUnit(a.getSendProQty());

            //特殊订单传入修改后的价格
            if (order.getOrderType().equals(1)) {
                order.setProductSkuPrice(a.getProductPrice());
            } else {
                StmChannelPrice stmChannelPrice = stmChannelPriceService.getOne
                        (new LambdaQueryWrapper<StmChannelPrice>().
                                eq(StmChannelPrice::getSkuCode, a.getProductSkuCode()).
                                eq(StmChannelPrice::getStoreId, order.getStoreId()));
                if (stmChannelPrice != null && stmChannelPrice.getPrice() != null) {
                    order.setProductSkuPrice(stmChannelPrice.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            }
            order.setFbiller(order.getCompanyCode());
            if (storeInfo != null) {
                order.setFbiller(storeInfo.getAccount());//设置创建人为经销商账号
            }
            BigDecimal rate = new BigDecimal(1);
            //优惠信息
            if (a.getFixedDiscountRate() != null && a.getFixedDiscountRate() != BigDecimal.ZERO) {
                order.setDiscrate(a.getFixedDiscountRate().multiply(rate));//传给sap的固定折扣需要在获取的折扣基础上*10
            } else {
                order.setDiscrate(BigDecimal.ZERO);
            }
            if (a.getProductDiscountRate() != null && a.getProductDiscountRate() != BigDecimal.ZERO) {
                order.setYhdisc(a.getProductDiscountRate().multiply(rate));//货物优惠折扣
            } else {
                order.setYhdisc(BigDecimal.ZERO);
            }
            if (a.getPromotionDiscountRate() != null && a.getPromotionDiscountRate() != BigDecimal.ZERO) {
                order.setCxdisc(a.getPromotionDiscountRate().multiply(rate));//促销折扣
            } else {
                order.setCxdisc(BigDecimal.ZERO);
            }
            if (a.getMissionDiscountRate() != null && a.getMissionDiscountRate() != BigDecimal.ZERO) {
                order.setRwdisc(a.getMissionDiscountRate().multiply(rate));//任务完成折扣
            } else {
                order.setRwdisc(BigDecimal.ZERO);
            }
            if (a.getAdjustDiscountRate() != null && a.getAdjustDiscountRate() != BigDecimal.ZERO) {
                order.setBcdisc(a.getAdjustDiscountRate().multiply(rate));//调价补差折扣
            } else {
                order.setBcdisc(BigDecimal.ZERO);
            }
            SapOrderCreateXML sapOrderCreateXML = SapConvert.INSTANCE.sapOrderCreateConvertXml(order);
            sapOrderCreateXML.setStoreId(order.getCompanyCode());
            sapOrderCreateXML.setVTWEG(order.getChannelId().toString());
            //新增组织公司编码 by martin 2024-10-10
            sapOrderCreateXML.setVkorg(order.getPartnerId().toString());
            //by martin 2024-08-27 订单号按照新规则
            if (!StringUtils.isEmpty(order.getOrderNo())) {
                sapOrderCreateXML.setId(order.getOrderNo());
            }
            sapOrderCreateXMLs.add(sapOrderCreateXML);
        }

        Map<String, String> map = sendToSap(toSapConfig, sapOrderCreateXMLs);
        String message = map.get("originalResult").toLowerCase();
        int beginIndex = message.lastIndexOf("<vbeln>");
        if (beginIndex > 0) {
            int endIndex = message.lastIndexOf("</vbeln>");
            String sapOrderNo = message.substring(beginIndex + 7, endIndex);
            log.info(order.getId() + "对应sap订单号:" + sapOrderNo);
            //设置SAP单号
            order.setVbeln(sapOrderNo);

            //未初审,金额足够直接复审需要补充初审信息
            if (StringUtils.isEmpty(order.getApplyBy())) {
                order.setApplyBy(userName);
                order.setApplyTime(new Date());

                OmsOrderTrace omsOrderTrace = new OmsOrderTrace();
                omsOrderTrace.setOrderId(order.getId());
                omsOrderTrace.setCreateBy(userName);
                omsOrderTrace.setCreateTime(new Date());
                omsOrderTrace.setLabel("订单初审通过");
                omsOrderTrace.setContent("通过");
                orderTraceService.save(omsOrderTrace);
            }

            //订单推送sap更新复审时间
            order.setCheckTime(new Date());
            order.setStatus(1);//复审状态
            omsOrderService.updateById(order);

            OmsOrderTrace omsOrderTrace = new OmsOrderTrace();
            omsOrderTrace.setOrderId(order.getId());
            omsOrderTrace.setCreateBy(userName);
            omsOrderTrace.setCreateTime(new Date());
            omsOrderTrace.setLabel("订单复审通过");
            omsOrderTrace.setContent("通过");
            orderTraceService.save(omsOrderTrace);
        }
        return map;
    }

    @Override
    public Map<String, String> toSapOrderCancel(String orderId) {
        OmsOrder order = omsOrderService.getById(orderId);
        if (order == null) {
            return null;
        }
        ToSapConfig toSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "sapOrderCreate_prd"));

        SapOrderCreateXML stmstoreInfoXML = SapConvert.INSTANCE.sapOrderCreateConvertXml(order);
        stmstoreInfoXML.setStoreId(order.getCompanyCode());
        Map<String, String> map = sendToSap(toSapConfig, stmstoreInfoXML);
        return map;
    }

    //订单结案
    @Override
    public boolean closeOrder(String orderId) {
        OmsOrder order = omsOrderService.getById(orderId);
        if (order == null || StringUtils.isEmpty(order.getStockBillNo())) {
            return false;
        }
        ToSapConfig toSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "sapOrderClose_prd"));
        SapCloseOrderReqXML sapOrderCloseXml = new SapCloseOrderReqXML();

        DateTime currentDate = DateTime.now();
        //格式化日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = dateFormat.format(currentDate);
        //格式化时间
        SimpleDateFormat timeFormat = new SimpleDateFormat("HHmmss");
        String timeStr = timeFormat.format(currentDate);
        //结案需要使用交货单号
        sapOrderCloseXml.setVBELN(order.getStockBillNo());
        sapOrderCloseXml.setPODAT(dateStr);
        sapOrderCloseXml.setPOTIM(timeStr);
        Map<String, String> map = sendToSap(toSapConfig, sapOrderCloseXml);
        String message = map.get("originalResult");
        int beginIndex = message.indexOf("<IT_RESULT>");
        if (beginIndex > 0) {
            String resultString = message.substring(beginIndex, message.indexOf("</IT_RESULT>") + 12);
            SapCloseOrderRespXML closeOrderRespXML = XStreamXmlBeanUtil.fromXml(resultString, SapCloseOrderRespXML.class);
            if (closeOrderRespXML != null && closeOrderRespXML.getItem() != null) {
                if ("确认成功".equals(closeOrderRespXML.getItem().getMESSAGE())) {
                    //结案后更新结案时间和状态
                    LambdaUpdateWrapper<OmsOrder> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(OmsOrder::getId, order.getId());
                    updateWrapper.set(OmsOrder::getReceiveTime, new Date());
                    updateWrapper.set(OmsOrder::getStatus, 3);
                    updateWrapper.set(OmsOrder::getConfirmStatus, 1);
                    omsOrderMapper.update(null, updateWrapper);

                    //订单轨迹
                    OmsOrderTrace trace = new OmsOrderTrace();
                    trace.setOrderId(orderId);
                    trace.setLabel("确认收货");
                    trace.setContent("您的订单已确认收货");
                    trace.setCreateTime(new Date());
                    omsOrderTraceMapper.insert(trace);

                    return true;
                }
            }
        }
        return false;
    }

    //订单撤销结案
    @Override
    public boolean revokeCloseOrder(OmsOrder order) {
        ToSapConfig toSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "revokeCloseOrder"));
        SapRevokeCloseOrderReqXML revokeCloseOrderReqXML = new SapRevokeCloseOrderReqXML();
        DateTime currentDate = DateTime.now();
        //格式化日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = dateFormat.format(currentDate);
        //格式化时间
        SimpleDateFormat timeFormat = new SimpleDateFormat("HHmmss");
        String timeStr = timeFormat.format(currentDate);
        //结案需要使用交货单号
        revokeCloseOrderReqXML.setVbeln(order.getStockBillNo());
        revokeCloseOrderReqXML.setPodat(dateStr);
        revokeCloseOrderReqXML.setPotim(timeStr);
        Map<String, String> map = sendToSap(toSapConfig, revokeCloseOrderReqXML);
        String message = map.get("originalResult");
        int beginIndex = message.indexOf("<ItResult>");
        if (beginIndex > 0) {
            String resultString = message.substring(beginIndex, message.indexOf("</ItResult>") + 11);
            SapRevokeCloseOrderRespXML revokeCloseOrderRespXML = XStreamXmlBeanUtil.fromXml(resultString, SapRevokeCloseOrderRespXML.class);
            if (revokeCloseOrderRespXML != null && revokeCloseOrderRespXML.getItem() != null) {
                if ("确认成功".equals(revokeCloseOrderRespXML.getItem().getMessage())) {
                    //撤销结案后更新状态为未结案和结案时间为空
                    LambdaUpdateWrapper<OmsOrder> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(OmsOrder::getId, order.getId());
                    updateWrapper.set(OmsOrder::getReceiveTime, null);
                    updateWrapper.set(OmsOrder::getStatus, 2);
                    updateWrapper.set(OmsOrder::getConfirmStatus, 0);
                    omsOrderMapper.update(null, updateWrapper);

                    //订单轨迹
                    OmsOrderTrace trace = new OmsOrderTrace();
                    trace.setOrderId(order.getId());
                    trace.setLabel("撤销结案");
                    trace.setContent("订单撤销结案");
                    trace.setCreateTime(new Date());
                    LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                    if (sysUser != null) {
                        trace.setCreateBy(sysUser.getRealname());
                    }
                    omsOrderTraceMapper.insert(trace);

                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 把对象转成xml对象，并转成xml格式，然后调用sap接口
     *
     * @param toSapConfig
     * @param xmlDto
     */
    private Map<String, String> sendToSap(ToSapConfig toSapConfig, Object xmlDto) {
        XStream xstream = new XStream();
        //XStream注解激活
        xstream.autodetectAnnotations(true);
        String item = xstream.toXML(xmlDto).replace("<list>", "").replace("</list>", "");
        try {
            String bodyXml = toSapConfig.getTemplateXml().replace("{urnCode}", toSapConfig.getUrnCode()).replace("{content}", item);
            bodyXml = bodyXml.replace("<>", "").replace("</>", "");
            Map<String, String> map = SapWebServiceRequestUtil.requestSap(toSapConfig.getWsdlUrl(), toSapConfig.getAction(), bodyXml);
            //记录下单的报文
            if (toSapConfig.getCode().equals("sapOrderCreate_prd")) {
                log.info("订单推送SAP报文-bodyXml\n", bodyXml);
                log.info("sendToSap:返回值\n", JSONUtil.toJsonStr(map));
                /* 取消sap接口日志记录，日志太多影响性能*/
                SysLog sysLog = new SysLog();
                //注解上的描述,操作日志内容
                sysLog.setLogContent(JSONUtil.toJsonStr(map));
                sysLog.setLogType(2);
                sysLog.setOperateType(2);
                sysLog.setRequestParam(bodyXml);
                sysLog.setMethod("sendToSap");
                sysLog.setIp("");
                sysLog.setUserid("sap");
                sysLog.setUsername("sap交互专用");
                sysLog.setCreateTime(new Date());
                //保存系统日志
                sysLogMapper.insert(sysLog);
            }
            return map;
        } catch (Exception e) {
            log.error("请求报错", e);
            Map<String, String> map = new HashMap<>(2);
            map.put("type", "E");
            map.put("message", e.getMessage());
            return map;
        }
    }

    /**
     * SAP获取固定折扣额度
     *
     * @param order
     * @param item
     */
    @Override
    public void getSapFixedDiscount(OmsOrder order, OmsOrderItem item) {
        if (order != null) {
            ToSapConfig toSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "sapFixedDiscount_prd"));
            SapFixedDiscountQueryXML sapFixedDiscountQueryXML = new SapFixedDiscountQueryXML();
            sapFixedDiscountQueryXML.setProductSkuCode(item.getProductSkuCode());
            sapFixedDiscountQueryXML.setChannelCode(order.getChannelId().toString());
            sapFixedDiscountQueryXML.setOrgCode(order.getPartnerId().toString());
            sapFixedDiscountQueryXML.setStoreId(order.getCompanyCode());
            Map<String, String> map = sendToSap(toSapConfig, sapFixedDiscountQueryXML);
            String message = map.get("originalResult");
            int beginIndex = message.indexOf("<TPriceMasterdata>");//找到折扣
            if (beginIndex > 0) {
                String discountString = message.substring(beginIndex, message.indexOf("</TPriceMasterdata>") + 19);
                SapFixedDiscountRespXML sapProductPriceRespXML = XStreamXmlBeanUtil.fromXml(discountString, SapFixedDiscountRespXML.class);
                if (sapProductPriceRespXML != null && sapProductPriceRespXML.getItemList() != null && !CollectionUtils.isEmpty(sapProductPriceRespXML.getItemList())) {
                    List<SapFixedDiscountRespXML.SapFixedDiscountItem> discountItemList = sapProductPriceRespXML.getItemList().stream().filter(x -> x.getKschl().equals("ZGZA")).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(discountItemList)) {
                        SapFixedDiscountRespXML.SapFixedDiscountItem discountItem = discountItemList.get(0);
                        BigDecimal discountRateResult = new BigDecimal(discountItem.getKbetr()).abs();
                        if (discountRateResult.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal discountRate = discountRateResult.divide(BigDecimal.valueOf(100));
                            item.setFixedDiscountRate(discountRate.multiply(BigDecimal.valueOf(100)));
                            if (item.getFixedDiscountAmount().compareTo(BigDecimal.ZERO) <= 0) {
                                item.setFixedDiscountAmount(item.getRealAmount().multiply(discountRate).multiply(BigDecimal.valueOf(item.getProductQuantity())));
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 更新经销商余额
     */
    @Override
    public void updateBalance(String storeId) {
        ToSapConfig toSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "distributorBalance_prd"));
        List<StmStoreInfo> storeInfoList = new ArrayList<>();
        if (!StringUtils.isEmpty(storeId)) {
            StmStoreInfo storeInfo = stmStoreInfoService.getByStoreId(Long.valueOf(storeId));
            if (storeInfo != null) {
                storeInfoList.add(storeInfo);
            }
        } else {
            storeInfoList = stmStoreInfoService.getStoreList();
        }
        if (!CollectionUtils.isEmpty(storeInfoList)) {
            storeInfoList.forEach(item -> {
                BigDecimal finalAmount = getStoreBalance(toSapConfig, item);
                BigDecimal oldAmount = item.getRemainCreditLimit() == null ? BigDecimal.ZERO : item.getRemainCreditLimit();
                if (finalAmount.compareTo(oldAmount) != 0) {
                    item.setRemainCreditLimit(finalAmount);
                    stmStoreInfoService.updateById(item);
                }
            });
        }
    }

    /**
     * 根据经销商ID查询余额
     */
    @Override
    public BigDecimal getBalance(String storeId) {
        ToSapConfig toSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "distributorBalance_prd"));
        if (!StringUtils.isEmpty(storeId)) {
            StmStoreInfo storeInfo = stmStoreInfoService.getByStoreId(Long.valueOf(storeId));
            BigDecimal finalAmount = getStoreBalance(toSapConfig, storeInfo);
            return finalAmount;
        }
        return BigDecimal.ZERO;
    }

    /**
     * 获取经销商余额
     */
    private BigDecimal getStoreBalance(ToSapConfig toSapConfig, StmStoreInfo storeInfo) {
        SapDistributorBalanceQueryXML sapDistributorBalanceQueryXML = new SapDistributorBalanceQueryXML();
        sapDistributorBalanceQueryXML.setKunnr(storeInfo.getCompanyCode().toString());
        sapDistributorBalanceQueryXML.setBukrs(storeInfo.getPartnerId().toString());
        sapDistributorBalanceQueryXML.setGjahr(String.valueOf(DateTime.now().year()));
        sapDistributorBalanceQueryXML.setMonth(String.valueOf(DateTime.now().month() + 1));
        Map<String, String> map = sendToSap(toSapConfig, sapDistributorBalanceQueryXML);
        String message = map.get("originalResult");
        int beginIndex = message.indexOf("<ItResult>");//找到折扣
        if (beginIndex > 0) {
            String resultString = message.substring(beginIndex, message.indexOf("</ItResult>") + 12);
            SapDistributorBalanceRespXML distributorBalanceRespXML = XStreamXmlBeanUtil.fromXml(resultString, SapDistributorBalanceRespXML.class);
            if (!CollectionUtils.isEmpty(distributorBalanceRespXML.getItemList())) {
                //期初余额
                BigDecimal lastBalance = distributorBalanceRespXML.getItemList().stream().filter(x -> x.getZctyp().equals("1")).findFirst().get().getZjine1().abs();
                BigDecimal receiveAmount = BigDecimal.ZERO;
                BigDecimal usedAmount = BigDecimal.ZERO;
                List<SapDistributorBalanceRespXML.DistributorBalanceItem> statementList = distributorBalanceRespXML.getItemList().stream().filter(x -> x.getZctyp().equals("2")).collect(Collectors.toList());
                for (SapDistributorBalanceRespXML.DistributorBalanceItem statementItem : statementList) {
                    receiveAmount = receiveAmount.add(statementItem.getZjine2h().abs());
                    usedAmount = usedAmount.add(statementItem.getZjine2s().abs());
                }
                BigDecimal finalAmount = lastBalance.add(receiveAmount).subtract(usedAmount);
                //订单传入SAP未开票占用的额度
                List<SapDistributorBalanceRespXML.DistributorBalanceItem> orderUseList = distributorBalanceRespXML.getItemList().stream().filter(x -> x.getZctyp().equals("5")).collect(Collectors.toList());
                for (SapDistributorBalanceRespXML.DistributorBalanceItem statementItem : orderUseList) {
                    finalAmount = finalAmount.subtract(statementItem.getZjine1().abs());
                }
                return finalAmount;
            }
        }
        return BigDecimal.ZERO;
    }

    /**
     * by martin 2024-06-28
     * 查询经销商可售和价格
     */
    @Override
    public void getSapProductPrice(Long partnerId, String storeId) {
        ToSapConfig productSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "distributorProduct_prd"));
        List<StmStoreInfo> storeInfoList = new ArrayList<>();
        if (!StringUtils.isEmpty(storeId)) {
            StmStoreInfo storeInfo = stmStoreInfoService.getByStoreId(Long.valueOf(storeId));
            if (storeInfo != null) {
                storeInfoList.add(storeInfo);
            }
        } else {
            if (partnerId != null) {
                storeInfoList = stmStoreInfoService.getStoreListByPartnerId(partnerId);
            } else {
                storeInfoList = stmStoreInfoService.getStoreList();
            }
        }

        if (!CollectionUtils.isEmpty(storeInfoList)) {
            ToSapConfig priceSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "distributorProductPrice_prd"));
            storeInfoList.forEach(storeInfo -> {
                SapDistributorProductQueryXML sapDistributorProductQueryXML = new SapDistributorProductQueryXML();
                sapDistributorProductQueryXML.setKUNNR(storeInfo.getCompanyCode());
                sapDistributorProductQueryXML.setVKORG(storeInfo.getPartnerId().toString());
                sapDistributorProductQueryXML.setVTWEG(storeInfo.getChannelId());
                //调用SAP接口查询可售商品
                Map<String, String> map = sendToSap(productSapConfig, sapDistributorProductQueryXML);
                String message = map.get("originalResult");
                int beginIndex = message.indexOf("<DATA_OUT>");//找到折扣
                if (beginIndex > 0) {
                    String resultString = message.substring(beginIndex, message.indexOf("</DATA_OUT>") + 11);
                    SapDistributorProductRespXML distributorProductRespXML = XStreamXmlBeanUtil.fromXml(resultString, SapDistributorProductRespXML.class);
                    if (!CollectionUtils.isEmpty(distributorProductRespXML.getItemList())) {

                        SapProductPriceQueryXML sapProductPriceQueryXML = new SapProductPriceQueryXML();
                        List<SapProductPriceItemXML> productPriceItemList = new ArrayList<>();
                        for (SapDistributorProductRespXML.SapDistributorProductItem product : distributorProductRespXML.getItemList()) {
                            SapProductPriceItemXML priceItem = new SapProductPriceItemXML();
                            priceItem.setKunnr(storeInfo.getCompanyCode());
                            priceItem.setVkorg(storeInfo.getPartnerId().toString());
                            priceItem.setVtweg(storeInfo.getChannelId());
                            priceItem.setMatnr(product.getMATNR());
                            productPriceItemList.add(priceItem);
                        }
                        sapProductPriceQueryXML.setItemList(productPriceItemList);
                        //根据可售商品查询价格
                        Map<String, String> priceMap = sendToSap(priceSapConfig, sapProductPriceQueryXML);
                        String priceMsg = priceMap.get("originalResult");
                        int priceBeginIndex = priceMsg.indexOf("<TPriceMasterdata>");//找到折扣
                        if (priceBeginIndex > 0) {
                            String priceResultString = priceMsg.substring(priceBeginIndex, priceMsg.indexOf("</TPriceMasterdata>") + 19);
                            SapProductPriceRespXML sapProductPriceRespXML = XStreamXmlBeanUtil.fromXml(priceResultString, SapProductPriceRespXML.class);
                            //新增或者修改经销商可售商品及价格
                            updateChannelPrice(distributorProductRespXML.getItemList(), sapProductPriceRespXML.getItemList(), storeInfo);
                        }
                    }
                }
            });
        }
    }

    /*
     * by martin 2024-06-28
     * 根据接口返回的结果处理系统数据
     * */
    private void updateChannelPrice(List<SapDistributorProductRespXML.SapDistributorProductItem> productList, List<SapProductPriceRespXML.SapProductPriceItem> priceResultList, StmStoreInfo storeInfo) {
        //当前经销商已有的可售及价格信息
        List<StmChannelPrice> existChannelPriceList = stmChannelPriceService.getByStoreId(storeInfo.getStoreId().toString());
        List<Integer> deleteIds = new ArrayList<>();
        existChannelPriceList.forEach(t -> {
            //原有的可售的商品在新的列表不存在,需要删除
            List<SapDistributorProductRespXML.SapDistributorProductItem> list = productList.stream().filter(p -> p.getMATNR().equals(t.getSkuCode())).collect(Collectors.toList());
            if (list == null || list.isEmpty()) {
                deleteIds.add(t.getId());
            }
        });
        //删除原可售有而新可售没有的数据
        stmChannelPriceService.removeByIds(deleteIds);
        if (priceResultList != null && !CollectionUtils.isEmpty(priceResultList)) {
            for (SapDistributorProductRespXML.SapDistributorProductItem product : productList) {
                //获取当前商品的价格列表
                List<SapProductPriceRespXML.SapProductPriceItem> priceList = priceResultList.stream().filter(x -> x.getKschl().equals("ZPRB") && x.getMatnr().equals(product.getMATNR())).collect(Collectors.toList());
                BigDecimal price = BigDecimal.ZERO;
                if (priceList != null && !priceList.isEmpty()) {
                    //经销商商品价格->销售部门商品价格->渠道价格
                    List<SapProductPriceRespXML.SapProductPriceItem> custPriceList = priceList.stream().filter(x -> StringUtils.isNotEmpty(x.getKunnr())).collect(Collectors.toList());
                    if (custPriceList != null && !custPriceList.isEmpty()) {
                        price = new BigDecimal(custPriceList.get(0).getKbetr());
                    } else {
                        String groupId = storeInfo.getGroupId() == null ? "" : storeInfo.getGroupId().toString();
                        List<SapProductPriceRespXML.SapProductPriceItem> deptPriceList = priceList.stream().filter(x -> StringUtils.isEmpty(x.getKunnr()) && StringUtils.isNotEmpty(x.getVkbur()) && x.getVkbur().equals(groupId)).collect(Collectors.toList());
                        if (deptPriceList != null && !deptPriceList.isEmpty()) {
                            price = new BigDecimal(deptPriceList.get(0).getKbetr());
                        } else {
                            List<SapProductPriceRespXML.SapProductPriceItem> channelPriceList = priceList.stream().filter(x -> StringUtils.isEmpty(x.getKunnr()) && StringUtils.isEmpty(x.getVkbur()) && x.getVtweg().equals(storeInfo.getChannelId())).collect(Collectors.toList());
                            if (channelPriceList != null && !channelPriceList.isEmpty()) {
                                price = new BigDecimal(channelPriceList.get(0).getKbetr());
                            } else {
                                List<SapProductPriceRespXML.SapProductPriceItem> orgPriceList = priceList.stream().filter(x -> StringUtils.isEmpty(x.getKunnr()) && StringUtils.isEmpty(x.getVkbur()) && StringUtils.isEmpty(x.getVtweg())).collect(Collectors.toList());
                                if (orgPriceList != null && !orgPriceList.isEmpty()) {
                                    price = new BigDecimal(orgPriceList.get(0).getKbetr());
                                }
                            }
                        }
                    }
                }
                if (price.compareTo(BigDecimal.ZERO) > 0) {
                    List<StmChannelPrice> tempChannelPriceList = existChannelPriceList.stream().filter(p -> p.getSkuCode().equals(product.getMATNR())).collect(Collectors.toList());
                    //原来已经存在需要更新
                    if (tempChannelPriceList != null && !tempChannelPriceList.isEmpty()) {
                        StmChannelPrice channelPrice = tempChannelPriceList.get(0);
                        if (channelPrice.getPrice().compareTo(price) != 0) {//价格不同的更新,相同的不更新
                            channelPrice.setPrice(price);
                            channelPrice.setUpdateTime(new Date());
                            stmChannelPriceService.updateById(channelPrice);
                        }
                    } else//原来可售不存在需要新增
                    {
                        StmChannelPrice channelPrice = new StmChannelPrice();
                        channelPrice.setPartnerId(storeInfo.getPartnerId());
                        channelPrice.setStoreId(storeInfo.getStoreId().toString());
                        channelPrice.setChannelId(storeInfo.getChannelId());
                        channelPrice.setSkuCode(product.getMATNR());
                        channelPrice.setPrice(price);
                        channelPrice.setStatus(1);
                        channelPrice.setCreateTime(new Date());
                        stmChannelPriceService.save(channelPrice);
                    }
                }
            }
        }
    }

    @Override
    public void pushOrderToSap() {
        LambdaQueryWrapper<OmsOrder> query = new LambdaQueryWrapper<OmsOrder>();
        query.eq(OmsOrder::getStatus, 5).isNull(OmsOrder::getVbeln).isNull(OmsOrder::getCheckTime);
        List<OmsOrder> orderList = omsOrderMapper.selectList(query);
        if (!CollectionUtils.isEmpty(orderList)) {
            //把订单按照提交时间排序，先下单的先复审
            Collections.sort(orderList, Comparator.comparing(OmsOrder::getCreateTime));
            orderList.forEach(item -> {
                if (item.getPartnerId() != null || item.getPartnerId() > 0) {
                    BigDecimal balance = getBalance(item.getStoreId().toString());
                    //如果此经销商订单前有初审的订单，需要扣除其占用金额 by martin 2024-08-21 14:23
                    List<OmsOrder> auditOrderList = omsOrderService.getAuditOrderList(item);
                    if (!auditOrderList.isEmpty()) {
                        for (OmsOrder o : auditOrderList) {
                            if (o.getPayAmount() != null) {
                                balance = balance.subtract(o.getPayAmount());
                            }
                        }
                    }
                    //获取经销商余额，如果余额大于等于订单金额，则推送SAP
                    if (balance != null && balance.compareTo(item.getPayAmount()) >= 0) {
                        toSapOrder(item, item.getId(), "system");
                    }
                }
            });
        }
    }

    @Override
    public void updateDealerDiscount(Long partnerId, String storeId) {
        List<StmStoreInfo> storeInfoList = new ArrayList<>();
        if (!StringUtils.isEmpty(storeId)) {
            StmStoreInfo storeInfo = stmStoreInfoService.getByStoreId(Long.valueOf(storeId));
            if (storeInfo != null) {
                storeInfoList.add(storeInfo);
            }
        } else {
            storeInfoList = stmStoreInfoService.getStoreList().stream().filter(x -> x.getPartnerId().equals(partnerId)).collect(Collectors.toList());
        }
        ToSapConfig discountSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "distributorDiscount_prd"));
        if (!CollectionUtils.isEmpty(storeInfoList)) {
            SapDistributorDiscountQueryXML discountQueryXML = new SapDistributorDiscountQueryXML();
            SapKunnrXML sapKunnrXML = new SapKunnrXML();
            List<SapKunnrItemXML> kunnrItemXMLList = new ArrayList<>();
            storeInfoList.forEach(item -> {
                SapKunnrItemXML kunnrItemXML = new SapKunnrItemXML();
                kunnrItemXML.setKunnr(item.getCompanyCode());
                kunnrItemXMLList.add(kunnrItemXML);
            });
            sapKunnrXML.setItemList(kunnrItemXMLList);
            discountQueryXML.setKunnr(sapKunnrXML);
            discountQueryXML.setVkorg(partnerId.toString());

            Map<String, String> map = sendToSap(discountSapConfig, discountQueryXML);
            String message = map.get("originalResult");
            int beginIndex = message.indexOf("<TPreQuota>");//找到折扣
            if (beginIndex > 0) {
                String resultString = message.substring(beginIndex, message.indexOf("</TPreQuota>") + 12);
                SapDistributorDiscountRespXML distributorProductRespXML = XStreamXmlBeanUtil.fromXml(resultString, SapDistributorDiscountRespXML.class);
                if (!CollectionUtils.isEmpty(distributorProductRespXML.getItemList())) {
                    List<String> channelList = distributorProductRespXML.getItemList().stream().map(x -> x.getVtweg()).distinct().collect(Collectors.toList());
                    final List<StmStoreInfo> storeList = storeInfoList;
                    //返回的结果可能存在多渠道,按照渠道循环
                    channelList.forEach(c -> {
                        //循环经销商
                        storeList.forEach(x -> {
                            List<SapDistributorDiscountRespXML.SapDistributorDiscountItem> tempList = distributorProductRespXML.getItemList().stream().filter(t -> t.getKunnr().equals(x.getCompanyCode().toString()) && t.getVtweg().equals(c)).collect(Collectors.toList());
                            if (tempList != null && !tempList.isEmpty()) {
                                QueryWrapper<StmDealerDiscount> discountQuery = new QueryWrapper<>();
                                discountQuery.eq("store_id", x.getCompanyCode());
                                discountQuery.eq("company_code", x.getPartnerId());
                                discountQuery.eq("channel_code", c);
                                List<StmDealerDiscount> discountList = dealerDiscountMapper.selectList(discountQuery);
                                if (discountList != null && !discountList.isEmpty())//修改当前折扣信息
                                {
                                    StmDealerDiscount dealerDiscount = discountList.get(0);
                                    StmDealerDiscount temp = new StmDealerDiscount();
                                    discountCalcuAmount(tempList, temp);
                                    discountCalcuAmount(tempList, dealerDiscount);
                                    if (dealerDiscount.getProductRemainAmount().compareTo(temp.getProductRemainAmount()) != 0 || dealerDiscount.getPromotionRemainAmount().compareTo(temp.getPromotionRemainAmount()) != 0
                                            || dealerDiscount.getAdjustRemainAmount().compareTo(temp.getAdjustRemainAmount()) != 0 || dealerDiscount.getMissionRemainAmount().compareTo(temp.getMissionRemainAmount()) != 0) {
                                        //如果可用余额有变化才更新否则不更新
                                        dealerDiscountMapper.updateById(dealerDiscount);
                                    }
                                } else {//新增经销商折扣信息
                                    StmDealerDiscount dealerDiscount = new StmDealerDiscount();
                                    dealerDiscount.setStoreId(x.getCompanyCode().toString());
                                    dealerDiscount.setCompanyCode(x.getPartnerId().toString());
                                    dealerDiscount.setChannelCode(c);
                                    discountCalcuAmount(tempList, dealerDiscount);
                                    dealerDiscountMapper.insert(dealerDiscount);
                                }
                            }
                        });
                    });
                }
            } else {
                if (!CollectionUtils.isEmpty(storeInfoList)) {
                    storeInfoList.forEach(storeInfo -> {
                        if (storeInfo != null) {
                            QueryWrapper<StmDealerDiscount> discountQuery = new QueryWrapper<>();
                            discountQuery.eq("store_id", storeInfo.getCompanyCode());
                            discountQuery.eq("company_code", storeInfo.getPartnerId());
                            discountQuery.eq("channel_code", storeInfo.getChannelId());
                            List<StmDealerDiscount> discountList = dealerDiscountMapper.selectList(discountQuery);
                            if (discountList != null && !discountList.isEmpty())//修改当前折扣信息
                            {
                                StmDealerDiscount discount = discountList.get(0);
                                BigDecimal amount = BigDecimal.ZERO;
                                discount.setProductAmount(amount);
                                discount.setProductRemainAmount(amount);
                                discount.setPromotionAmount(amount);
                                discount.setPromotionRemainAmount(amount);
                                discount.setMissionAmount(amount);
                                discount.setMissionRemainAmount(amount);
                                discount.setAdjustAmount(amount);
                                discount.setAdjustRemainAmount(amount);
                                discount.setAuditStatus(1);
                                dealerDiscountMapper.updateById(discount);
                            } else {
                                StmDealerDiscount discount = new StmDealerDiscount();
                                BigDecimal amount = BigDecimal.ZERO;
                                discount.setStoreId(storeInfo.getCompanyCode());
                                discount.setCompanyCode(storeInfo.getPartnerId().toString());
                                discount.setChannelCode(storeInfo.getChannelId());
                                discount.setProductAmount(amount);
                                discount.setProductRemainAmount(amount);
                                discount.setPromotionAmount(amount);
                                discount.setPromotionRemainAmount(amount);
                                discount.setMissionAmount(amount);
                                discount.setMissionRemainAmount(amount);
                                discount.setAdjustAmount(amount);
                                discount.setAdjustRemainAmount(amount);
                                discount.setAuditStatus(1);
                                dealerDiscountMapper.insert(discount);
                            }
                        }
                    });
                }
            }
        }
    }

    //根据获取的结果处理折扣上的数据
    private void discountCalcuAmount(List<SapDistributorDiscountRespXML.SapDistributorDiscountItem> itemList, StmDealerDiscount discount) {
        if (itemList != null && !itemList.isEmpty() && discount.getId() != null) {
            itemList.forEach(x -> {
                switch (x.getKschl()) {
                    case "ZBZA"://货物优惠折扣
                        discount.setProductAmount(new BigDecimal(x.getZZkjh()));
                        discount.setProductRemainAmount(new BigDecimal(x.getZRest()));
                        break;
                    case "ZCXF"://促销费用
                        discount.setPromotionAmount(new BigDecimal(x.getZZkjh()));
                        discount.setPromotionRemainAmount(new BigDecimal(x.getZRest()));
                        break;
                    case "ZFLA"://任务完成
                        discount.setMissionAmount(new BigDecimal(x.getZZkjh()));
                        discount.setMissionRemainAmount(new BigDecimal(x.getZRest()));
                        break;
                    case "ZTJB"://调价补差
                        discount.setAdjustAmount(new BigDecimal(x.getZZkjh()));
                        discount.setAdjustRemainAmount(new BigDecimal(x.getZRest()));
                        break;
                    default:
                        break;
                }
            });
            discount.setAuditStatus(1);
        } else {
            BigDecimal amount = BigDecimal.ZERO;
            discount.setProductAmount(amount);
            discount.setProductRemainAmount(amount);
            discount.setPromotionAmount(amount);
            discount.setPromotionRemainAmount(amount);
            discount.setMissionAmount(amount);
            discount.setMissionRemainAmount(amount);
            discount.setAdjustAmount(amount);
            discount.setAdjustRemainAmount(amount);
            discount.setAuditStatus(1);
        }
    }

    /**
     * 获取经销商对账单
     */
    public void getStatement(Long partnerId, String storeId, String year, String month) {
        List<StmStoreInfo> storeInfoList = new ArrayList<>();
        if (!StringUtils.isEmpty(storeId)) {
            StmStoreInfo storeInfo = stmStoreInfoService.getByStoreId(Long.valueOf(storeId));
            if (storeInfo != null) {
                storeInfoList.add(storeInfo);
            }
        } else {
            storeInfoList = stmStoreInfoService.getStoreList().stream().filter(x -> x.getPartnerId().equals(partnerId)).collect(Collectors.toList());
        }
        ToSapConfig toSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "distributorStatement_prd"));
        if (storeInfoList != null && !CollectionUtils.isEmpty(storeInfoList)) {
            storeInfoList.forEach(storeInfo -> {
                SapDistributorStatementQueryXML sapDistributorStatementQueryXML = new SapDistributorStatementQueryXML();
                sapDistributorStatementQueryXML.setKUNNR(storeInfo.getCompanyCode());
                sapDistributorStatementQueryXML.setBUKRS(storeInfo.getPartnerId().toString());

                String parmYear = String.valueOf(DateTime.now().year());
                String parmMonth = String.valueOf(DateTime.now().month() + 1);
                if (StringUtils.isNotEmpty(year) && !year.equals("0")) {
                    parmYear = year;
                }
                if (StringUtils.isNotEmpty(month) && !month.equals("0")) {
                    parmMonth = month;
                }
                sapDistributorStatementQueryXML.setGJAHR(parmYear);
                sapDistributorStatementQueryXML.setMONTH(parmMonth);
                Map<String, String> map = sendToSap(toSapConfig, sapDistributorStatementQueryXML);
                String message = map.get("originalResult");
                int beginIndex = message.indexOf("<IT_RESULT>");//找到折扣
                if (beginIndex > 0) {
                    String resultString = message.substring(beginIndex, message.indexOf("</IT_RESULT>") + 12);
                    SapDistributorStatementRespXML distributorStatementRespXML = XStreamXmlBeanUtil.fromXml(resultString, SapDistributorStatementRespXML.class);
                    if (!CollectionUtils.isEmpty(distributorStatementRespXML.getItemList())) {
                        QueryWrapper<StmDealerStatement> query = new QueryWrapper<>();
                        query.eq("store_id", storeInfo.getCompanyCode()).eq("partner_id", storeInfo.getPartnerId())
                                .eq("bill_year", parmYear).eq("bill_month", parmMonth);
                        List<StmDealerStatement> statementList = dealerStatementMapper.selectList(query);
                        if (statementList.stream().count() != distributorStatementRespXML.getItemList().stream().count()) {
                            if (!CollectionUtils.isEmpty(statementList)) {
                                //删除现有对账单数据
                                dealerStatementMapper.delete(query);
                            }

                            //插入对账单数据
                            SimpleDateFormat datefmt = new SimpleDateFormat("yyyy-MM-dd");
                            distributorStatementRespXML.getItemList().forEach(item -> {
                                StmDealerStatement statement = new StmDealerStatement();
                                statement.setPartnerId(Integer.valueOf(item.getBUKRS()));
                                statement.setStoreId(item.getKUNNR());
                                statement.setBillYear(Integer.valueOf(item.getGJAHR()));
                                statement.setBillMonth(Integer.valueOf(item.getZMONTH()));
                                try {
                                    statement.setBillDate(datefmt.parse(item.getBUDAT()));
                                } catch (ParseException e) {
                                    statement.setBillDate(null);
                                }
                                statement.setBillNote(item.getSGTXT());
                                statement.setBillType(Integer.valueOf(item.getZCTYP()));
                                statement.setCreditAmount(item.getZJINE2H());//转账
                                statement.setDebitAmount(item.getZJINE2S());//使用
                                statement.setBalanceAmount(BigDecimal.ZERO);
                                statement.setCreateTime(DateTime.now());
                                dealerStatementMapper.insert(statement);
                            });
                            //计算账单
                            calcStatement(dealerStatementMapper.selectList(query), storeInfo, Integer.valueOf(parmYear), Integer.valueOf(parmMonth));
                        }
                    }
                }
            });
        }
    }

    //初审后超过48个小时未复审的订单自动取消
    @Override
    public void autoOrderCancel() {
        Integer overtimeHours = 48;
        OmsOrderSetting setting = omsOrderSettingMapper.selectById(1);
        if (setting != null) {
            overtimeHours = setting.getNormalOrderOvertime();
        }
        QueryWrapper<OmsOrder> orderQuery = new QueryWrapper();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR, 0 - overtimeHours);
        Date newdate = calendar.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        orderQuery.lt("apply_time", formatter.format(newdate));
        orderQuery.eq("status", 5);//初审状态
        List<OmsOrder> orderList = omsOrderMapper.selectList(orderQuery);
        if (orderList != null && !orderList.isEmpty()) {
            orderList.forEach(x -> {
                UpdateWrapper<OmsOrder> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", x.getId());
                updateWrapper.set("status", 4);//修改订单状态为作废状态
                updateWrapper.set("update_time", new Date());
                //updateWrapper.set("apply_time", null);
                //updateWrapper.set("apply_by", "");
                omsOrderMapper.update(null, updateWrapper);
            });
        }
    }

    private void calcStatement(List<StmDealerStatement> statementList, StmStoreInfo storeInfo, Integer year, Integer month) {
        List<StmDealerStatement> amountList = statementList.stream().filter(x -> x.getBillType().equals(2)).collect(Collectors.toList());
        Collections.sort(amountList, Comparator.comparing(StmDealerStatement::getBillDate));
        BigDecimal zero = BigDecimal.ZERO;
        BigDecimal lastBalance = BigDecimal.ZERO;
        BigDecimal sumCreditAmount = BigDecimal.ZERO;
        BigDecimal sumDebitAmount = BigDecimal.ZERO;
        for (StmDealerStatement item : amountList) {
            if (item.getCreditAmount().compareTo(zero) > 0) {//充值
                lastBalance = lastBalance.subtract(item.getCreditAmount());
                item.setBalanceAmount(lastBalance);
                sumCreditAmount = sumCreditAmount.add(item.getCreditAmount());
                dealerStatementMapper.updateById(item);
            }
            if (item.getDebitAmount().compareTo(zero) > 0) {//充值
                lastBalance = lastBalance.add(item.getDebitAmount());
                item.setBalanceAmount(lastBalance);
                sumDebitAmount = sumDebitAmount.add(item.getDebitAmount());
                dealerStatementMapper.updateById(item);
            }
        }
        List<StmDealerStatement> totalMonthList = statementList.stream().filter(x -> x.getBillType().equals(3)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(totalMonthList)) {
            StmDealerStatement monthTotal = totalMonthList.get(0);
            monthTotal.setCreditAmount(sumCreditAmount);
            monthTotal.setDebitAmount(sumDebitAmount);
            monthTotal.setBalanceAmount(sumDebitAmount.subtract(sumCreditAmount));
            dealerStatementMapper.updateById(monthTotal);
        }
        List<StmDealerStatement> totalYearList = statementList.stream().filter(x -> x.getBillType().equals(4)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(totalYearList)) {
            StmDealerStatement yearTotal = totalYearList.get(0);
            QueryWrapper<StmDealerStatement> query = new QueryWrapper<>();
            query.eq("store_id", storeInfo.getCompanyCode()).eq("partner_id", storeInfo.getPartnerId())
                    .eq("bill_year", year).le("bill_month", month).eq("bill_type", 2);
            List<StmDealerStatement> allYearList = dealerStatementMapper.selectList(query);
            BigDecimal sumYearCreditAmount = BigDecimal.ZERO;
            BigDecimal sumYearDebitAmount = BigDecimal.ZERO;
            if (!CollectionUtils.isEmpty(allYearList)) {
                for (StmDealerStatement statement : allYearList) {
                    sumYearCreditAmount = sumYearCreditAmount.add(statement.getCreditAmount());
                    sumYearDebitAmount = sumYearDebitAmount.add(statement.getDebitAmount());
                }
            }
            yearTotal.setCreditAmount(sumYearCreditAmount);
            yearTotal.setDebitAmount(sumYearDebitAmount);
            yearTotal.setBalanceAmount(sumYearDebitAmount.subtract(sumYearCreditAmount));
            dealerStatementMapper.updateById(yearTotal);
        }
    }

    /**
     * 同步已删除交货单状态
     */
    @Override
    public void updateOutStockStatus(Long partnerId, String orderId) {
        List<OmsOrder> orderList = new ArrayList<>();
        if (!StringUtils.isEmpty(orderId)) {
            OmsOrder order = omsOrderService.getById(orderId);
            if (order != null) {
                orderList.add(order);
            }
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.HOUR, 0 - 24 * 5);
            Date newdate = calendar.getTime();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<Integer> statusList = new ArrayList<>();
            statusList.add(4);
            statusList.add(8);
            QueryWrapper<OmsOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.isNotNull("vbeln");
            queryWrapper.ge("check_time", formatter.format(newdate));
            queryWrapper.eq("partner_id", partnerId);
            queryWrapper.eq("delete_status", 0);
            queryWrapper.notIn("status", statusList);
            //查询近一个月订单
            orderList = omsOrderMapper.selectList(queryWrapper);
        }
        if (orderList.isEmpty()) {
            return;
        }
        ToSapConfig toSapConfig = toSapConfigMapper.selectOne(new LambdaQueryWrapper<ToSapConfig>().eq(ToSapConfig::getCode, "stockBillStatus_prd"));
        if (!orderList.isEmpty()) {
            List<SapVbelnXML> vbelnList = new ArrayList<>();
            SapStockBillQueryXML stockBillQueryXML = new SapStockBillQueryXML();
            orderList.forEach(x -> {
                if (!StringUtils.isEmpty(x.getVbeln())) {
                    SapVbelnXML vbelnXML = new SapVbelnXML();
                    vbelnXML.setVgbel(x.getVbeln());
                    vbelnList.add(vbelnXML);
                }
            });
            if (vbelnList.isEmpty()) {
                return;
            }
            stockBillQueryXML.setVbelnList(vbelnList);
            Map<String, String> map = sendToSap(toSapConfig, stockBillQueryXML);
            String message = map.get("originalResult");
            int beginIndex = message.indexOf("<TVbelnVl>");//找到折扣
            if (beginIndex > 0) {
                String resultString = message.substring(beginIndex, message.indexOf("</TVbelnVl>") + 11);
                SapStockBillRespXML sapStockBillRespXML = XStreamXmlBeanUtil.fromXml(resultString, SapStockBillRespXML.class);
                if (sapStockBillRespXML != null && !sapStockBillRespXML.getItemList().isEmpty()) {
                    orderList.forEach(order -> {
                        List<SapStockBillXML> stockBillList = sapStockBillRespXML.getItemList().stream().filter(x -> x.getVgbel().equals(order.getVbeln())).collect(Collectors.toList());
                        if (!stockBillList.isEmpty()) {//订单查询到了对应的交货单
                            SapStockBillXML stockBill = stockBillList.get(0);
                            //订单上交货单号为空更新交货单号和出库时间
                            if ((StringUtils.isEmpty(order.getStockBillNo()) && !StringUtils.isEmpty(stockBill.getVbelnVl())) || (!StringUtils.isEmpty(stockBill.getVbelnVl()) && !stockBill.getVbelnVl().equals(order.getStockBillNo()))) {
                                String dateString = stockBill.getErdat() + " " + stockBill.getErzet();
                                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                                UpdateWrapper<OmsOrder> updateWrapper = new UpdateWrapper<>();
                                updateWrapper.eq("id", order.getId());
                                updateWrapper.set("status", 11);
                                updateWrapper.set("stock_bill_no", stockBill.getVbelnVl());
                                updateWrapper.set("update_time", new Date());
                                try {
                                    updateWrapper.set("outbound_time", formatter.parse(dateString));
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                omsOrderMapper.update(null, updateWrapper);

                                //增加订单出库日志
                                OmsOrderTrace orderTrace = new OmsOrderTrace();
                                orderTrace.setOrderId(order.getId());
                                orderTrace.setLabel("订单出库");
                                orderTrace.setContent("您的订单已出库");
                                orderTrace.setCreateBy("system");
                                try {
                                    orderTrace.setCreateTime(formatter.parse(dateString));
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                omsOrderTraceMapper.insert(orderTrace);
                            } else//交货单号不为空
                            {
                                if (StringUtils.isEmpty(stockBill.getVbelnVl())) {//查询返回结果上交货单号是否为空，为空说明删除
                                    UpdateWrapper<OmsOrder> updateWrapper = new UpdateWrapper<>();
                                    updateWrapper.eq("id", order.getId());
                                    updateWrapper.set("status", 1);
                                    updateWrapper.set("update_time", new Date());
                                    updateWrapper.set("outbound_time", null);
                                    omsOrderMapper.update(null, updateWrapper);
                                }
                            }
                        }
                    });
                }
            }
        }
    }

    @Override
    public void updateStoreDisabledStatus(String storeId) {
        List<StmStoreInfo> storeList = new ArrayList<>();
        if (!StringUtils.isEmpty(storeId)) {
            StmStoreInfo storeInfo = stmStoreInfoService.getByStoreId(Long.valueOf(storeId));
            if (storeInfo != null) {
                storeList.add(storeInfo);
            }
        } else {
            storeList = stmStoreInfoService.getStoreInfoDisabledList();
        }
        if (!storeList.isEmpty()) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            storeList.forEach(x -> {
                if (x.getDisabledTime() != null && dateFormat.format(x.getDisabledTime()).equals(dateFormat.format(new Date()))) {
                    x.setDisabledStatus(1);
                    x.setUpdateTime(new Date());
                    stmStoreInfoService.updateById(x);
                }
            });
        }
    }

    @Override
    public void updateOutStockStatusRedis(String s, String s1) {

    }
}
